package router

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"aicloud.cn/aicloud-operate/pkg/db"
	"aicloud.cn/aicloud-operate/pkg/model"
	_const "aicloud.cn/aicloud-operate/pkg/util/const"
)

func (rt *Router) auth() gin.HandlerFunc {
	return nil
}

func (rt *Router) user() gin.HandlerFunc {
	return func(c *gin.Context) {
		userId := c.MustGet("user_id").(string)

		user, err := db.DbClient.GetUserById(userId)
		if err != nil {
			Fail(c, http.StatusUnauthorized, err)
			return
		}
		c.Set("user", user)
		c.Set("tenant_id", user.TenantID)
		//c.Set("isadmin", user.IsAdmin())
		c.Next()
	}
}

func (rt *Router) admin() gin.HandlerFunc {
	return func(c *gin.Context) {
		userId := c.MustGet("user_id").(string)

		user, err := db.DbClient.GetUserById(userId)
		if err != nil {
			Fail(c, http.StatusUnauthorized, err)
			return
		}
		if user == nil {
			Fail(c, http.StatusUnauthorized, fmt.Errorf("认证失败"))
			return
		}
		found := false
		for _, roleId := range user.RoleIdList {
			if roleId == _const.ADMIN {
				found = true
				break
			}
		}
		if !found {
			Fail(c, http.StatusForbidden, fmt.Errorf("权限不足"))
			return
		}
		c.Set("user", user)
		c.Next()
	}
}

func (rt *Router) perm(operation string) gin.HandlerFunc {
	return func(c *gin.Context) {
		user := c.MustGet("user").(*model.User)
		pass, err := checkPerm(operation, *user)
		if err != nil {
			Fail(c, http.StatusInternalServerError, err)
			return
		}
		if !pass {
			Fail(c, http.StatusForbidden, fmt.Errorf("没有权限"))
			return
		}
		c.Next()
	}
}

func checkPerm(operation string, user model.User) (bool, error) {
	if user.IsAdmin() {
		return true, nil
	}
	return roleHasOperation(user.RoleIdList, operation)
}

func roleHasOperation(roleIds []string, operation string) (bool, error) {
	if len(roleIds) == 0 {
		return false, nil
	}
	return db.DbClient.Exist(db.DbClient.GetTx().Model(&model.RoleOperation{}).Where("operation = ? and role_id IN ?", operation, roleIds))
}
